package com.android.benbourahla.carmode.sms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

import com.android.benbourahla.carmode.utils.SMSUtils;
import com.android.benbourahla.carmode.utils.Utils;

public class SMSReceiver extends BroadcastReceiver implements
		TextToSpeech.OnInitListener
{

	// private Context context = null;
	private SharedPreferences					settings	= null;
	private SharedPreferences.Editor	editor		= null;
	private boolean										isAppActivate;

	@Override
	public void onReceive(Context context, Intent intent)
	{
		settings = context.getSharedPreferences(Utils.sharedName, 0);
		isAppActivate = settings.getBoolean("IS_APP_ACTIVATED", false);
		editor = settings.edit();
		Utils.DisplayToast(context, "OnReceive", Toast.LENGTH_LONG);
		Log.i("SMSReceiver", intent.getAction());
		// this.context = context;
		// initData();

		if (intent.getAction().equals(SMSUtils.ACTION_RECEIVE_SMS))
		{
			if (isAppActivate == true)
			{
				Bundle bundle = intent.getExtras();
				if (bundle != null)
				{
					Object[] pdus = (Object[]) bundle.get("pdus");

					final SmsMessage[] messages = new SmsMessage[pdus.length];
					for (int i = 0; i < pdus.length; i++)
					{
						messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
					}

					if (messages.length > -1)
					{
						// Verification du message
						final String messageBody = messages[0].getMessageBody();
						final String phoneNumber = messages[0]
								.getDisplayOriginatingAddress();
						Log.i("SMSReceiver", messageBody);
						Log.i("SMSReceiver", Boolean.toString(SMSUtils.IS_APP_ACTIVATE));
						if (isAppActivate == true)
						{
							editor.putString("messageBody", messageBody);
							editor.putString("phoneNumber", phoneNumber);
							editor.commit();
						}
						else
						{
							editor.putString("messageBody", "");
							editor.putString("phoneNumber", "");
							editor.commit();
						}
					}
				}
			}
		}
	}

	@Override
	public void onInit(int arg0)
	{

	}
}
